﻿using AutoMapper;
using Common.Enum;
using Entity.WMS.DTO.WarehouseOtherIn;
using Entity.WMS.Entity;
using Entity.WMS.View.WarehouseOtherIn;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.WMS
{
    public class WarehouseOtherInService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * 自动映射
         */
        private readonly IMapper _mapper;

        /**
         * 构造注入
         */
        public WarehouseOtherInService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取其他入库单列表
         */
        public async Task<RequestResponseModel<PageResult<WarehouseOtherInView>>> GetWarehouseOtherInList(WarehouseOtherInSearchDTO warehouseOtherInSearchDTO)
        {
            //筛选
            var query = _context.WarehouseOtherInView
                .WhereIF(a => a.Code.Contains(warehouseOtherInSearchDTO.Code), !string.IsNullOrEmpty(warehouseOtherInSearchDTO.Code))
                .WhereIF(a => a.ExamStatus == warehouseOtherInSearchDTO.ExamStatus, warehouseOtherInSearchDTO.ExamStatus != null)
                ;

            //返回列表
            var warehouseOtherInList = await query
                .OrderBy(a => a.CreateTime)
                .Page(warehouseOtherInSearchDTO.CurrentPage, warehouseOtherInSearchDTO.PageSize)
                .ToListAsync();

            //总数据量
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<WarehouseOtherInView>(warehouseOtherInList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 获取其他入库单子单列表
         */
        public async Task<RequestResponseModel<PageResult<WarehouseOtherInItemView>>> GetWarehouseOtherInItemList(WarehouseOtherInItemSearchDTO warehouseOtherInItemSearchDTO)
        {
            //筛选
            var query = _context.WarehouseOtherInItemView
                .Where(a => a.WarehouseOtherInId == warehouseOtherInItemSearchDTO.Id)
                ;

            //返回列表
            var warehouseOtherInItemList = await query
                .Page(warehouseOtherInItemSearchDTO.CurrentPage, warehouseOtherInItemSearchDTO.PageSize)
                .ToListAsync();

            //总数据量
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<WarehouseOtherInItemView>(warehouseOtherInItemList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 新增其他入库单
         */
        public async Task<RequestResponseModel<string>> AddWarehouseOtherIn(WarehouseOtherInAddDTO warehouseOtherInAddDTO)
        {
            //处理主单单据
            var warehouseOtherIn = _mapper.Map<WarehouseOtherInModel>(warehouseOtherInAddDTO);
            warehouseOtherIn.Id = Guid.NewGuid().ToString();
            warehouseOtherIn.CreateTime = DateTime.Now;
            warehouseOtherIn.ExamStatus = StateEnum.ExamStatus.待审核;

            //处理子单单据
            var warehouseOtherInItem = _mapper.Map<List<WarehouseOtherInItemModel>>(warehouseOtherInAddDTO.Items);
            foreach (var item in warehouseOtherInItem)
            {
                item.Id = Guid.NewGuid().ToString();
                item.WarehouseOtherInId = warehouseOtherIn.Id;
            }

            //修改并保存数据库
            _context.WarehouseOtherIn.Add(warehouseOtherIn);
            _context.WarehouseOtherInItem.AddRange(warehouseOtherInItem);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "新增成功", warehouseOtherIn.Id);
        }

        /**
         * 删除其他入库单
         */
        public async Task<RequestResponseModel<string>> DeleteWarehouseOtherIn(string Id)
        {
            //校验id有效性
            var query = await Valid.ValidId(_context.WarehouseOtherIn, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "id无效", Id);
            }

            //已审核的单据无法删除
            if (query.ExamStatus == StateEnum.ExamStatus.审核通过)
            {
                return RequestResponse.CreateResponse(400, "审核通过的单据无法删除", Id);
            }

            //查找该id下的子单
            var warehouseOtherInItemList = _context.WarehouseOtherInItem
                .Where(a => a.Id.Equals(Id));

            //操作数据库并保存
            _context.WarehouseOtherIn.Remove(query);
            _context.WarehouseOtherInItem.RemoveRange(warehouseOtherInItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "删除成功", Id);
        }

        /**
         * 其他入库单 - 审核通过
         */
        public async Task<RequestResponseModel<string>> PassWarehouseOtherIn(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.WarehouseOtherIn, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核通过", Id);
            }

            //修改主单状态，并修改数据库
            query.ExamStatus = StateEnum.ExamStatus.审核通过;
            _context.WarehouseOtherIn.Update(query);

            //查找该单据的子单
            var warehouseOtherInItem = await _context.WarehouseOtherInItem
                .Where(a => a.WarehouseOtherInId.Equals(Id))
                .ToListAsync();

            //整合其他入库子单数据
            var goodsIdList = warehouseOtherInItem.Select(a => a.GoodsId).ToList();
            var warehouseIdList = warehouseOtherInItem.Select(a => a.WarehouseId).ToList();
            var warehousePositionIdList = warehouseOtherInItem.Select(a => a.WarehousePositionId).ToList();
            var batchNumberList = warehouseOtherInItem.Select(a => a.BatchNumber).ToList();

            //处理结存主单
            var warehouseBalanceList = await _context.WarehouseBalance
                .Where(a => goodsIdList.Contains(a.GoodsId))
                .ToListAsync()
                ;

            //处理仓库库存单
            var warehouseInventoryList = await _context.WarehouseInventory
                .Where(a => goodsIdList.Contains(a.GoodsId))
                .Where(a => warehouseIdList.Contains(a.WarehouseId))
                .Where(a => warehousePositionIdList.Contains(a.WarehousePositionId))
                .Where(a => batchNumberList.Contains(a.BatchNumber))
                .ToListAsync();

            // 处理每一个入库商品
            foreach (var item in warehouseOtherInItem)
            {
                //处理结存主单
                var balance = warehouseBalanceList.Find(a => a.GoodsId == item.GoodsId);
                if (balance == null)
                {
                    balance = _mapper.Map<WarehouseBalanceModel>(item);
                    balance.Id = Guid.NewGuid().ToString();
                    balance.Number_End = item.Number_In;
                    _context.WarehouseBalance.Add(balance);
                }
                else
                {
                    balance.Number_End += item.Number_In;
                    balance.Number_In += item.Number_In;
                    _context.WarehouseBalance.Update(balance);
                }

                //处理结存子单
                var balanceItem = _mapper.Map<WarehouseBalanceItemModel>(item);
                balanceItem.WarehouseBalanceId = balance.Id;
                balanceItem.Type = StateEnum.WarehouseType.其他入库;
                balanceItem.Number_Out = 0;
                balanceItem.Number_Real = balance.Number_End;
                balanceItem.CurrentPeriod = true;
                balanceItem.CreateTime = DateTime.Now;
                _context.WarehouseBalanceItem.Add(balanceItem);

                //处理仓库库存单
                var warehouseInventory = warehouseInventoryList.Find(a => a.GoodsId == item.GoodsId && a.WarehouseId == item.WarehouseId && a.WarehousePositionId == item.WarehousePositionId && a.BatchNumber == item.BatchNumber);
                if (warehouseInventory == null)
                {
                    warehouseInventory = _mapper.Map<WarehouseInventoryModel>(item);
                    warehouseInventory.Number_Real = item.Number_In;
                    _context.WarehouseInventory.Add(warehouseInventory);
                }
                else
                {
                    warehouseInventory.Number_Real += item.Number_In;
                    _context.WarehouseInventory.Update(warehouseInventory);
                }
            }

            //保存数据库
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核通过成功", Id);
        }

        /**
         * 其他入库单 - 审核不通过
         */
        public async Task<RequestResponseModel<string>> UnPassWarehouseOtherIn(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.WarehouseOtherIn, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核不通过", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核不通过;

            //修改并保存数据库
            _context.WarehouseOtherIn.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核不通过成功", Id);
        }

        /**
         * 其他入库单 - 反审核
         */
        public async Task<RequestResponseModel<string>> CancelPassWarehouseOtherIn(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.WarehouseOtherIn, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.审核不通过)
            {
                return RequestResponse.CreateResponse(400, "只有审核不通过的单据才可以反审核", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.待审核;

            //修改并保存数据库
            _context.WarehouseOtherIn.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "反审核成功", Id);
        }
    }
}
